<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>文件管理</title>
  <link rel="stylesheet" href="/component/pear/css/pear.css">
</head>
<body style="padding: 20px">
<div class="layui-form" style="margin-bottom: 50px">
  <div class="layui-col-md9">
    <div class="layui-input-group">
      <div class="layui-input-split layui-input-prefix">
        目录
      </div>
      <input style="width: 512px" type="text" id="path" placeholder="输入要访问的目录" class="layui-input">
      <div class="layui-input-suffix">
        <button id="toFolder" class="layui-btn layui-btn-primary">
          <i class="layui-icon layui-icon-release"></i>访问
        </button>
        <button id="toProject" class="layui-btn layui-btn-primary">
          <i class="layui-icon layui-icon-location"></i>项目目录
        </button>
        <button id="uploadFile" class="layui-btn layui-btn-primary">
          <i class="layui-icon layui-icon-upload-drag"></i>上传文件
        </button>
      </div>
    </div>
  </div>
</div>
<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="refresh"><i class="layui-icon layui-icon-refresh"></i>刷新列表
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="packageDownload"><i
              class="layui-icon layui-icon-download-circle"></i>打包下载
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="moveFile"><i
              class="layui-icon layui-icon-slider"></i>移动到
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="copyFile"><i
              class="layui-icon layui-icon-template-1"></i>复制到
    </button>
    <button class="layui-btn layui-btn-sm" lay-event="back"><i class="layui-icon layui-icon-return"></i>返回上一级目录
    </button>
  </div>
</script>
<script type="text/html" id="barDemo">
  <div class="layui-clear-space">
    <a class="layui-btn layui-btn-xs" lay-event="open">
      <i class="layui-icon layui-icon-eye"></i> 打开</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="download">
      <i class="layui-icon layui-icon-download-circle"></i> 打包下载
    </a>
    <a class="layui-btn layui-btn-xs" lay-event="rename" style="background-color: #07c160">
      <i class="layui-icon layui-icon-edit"></i> 重命名</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">
      <i class="layui-icon layui-icon-delete"></i> 删除</a>
  </div>
</script>
<script type="text/javascript" src="/component/layui/layui.js"></script>
<script type="text/javascript" src="/component/pear/pear.js"></script>
<script>
    function fDate(date) {
        let year = date.getFullYear(); // 获取年份
        let month = date.getMonth() + 1; // 获取月份（注意月份从0开始，所以我们需要加1）
        let day = date.getDate(); // 获取日期
        let hours = date.getHours(); // 获取小时
        let minutes = date.getMinutes(); // 获取分钟
        let seconds = date.getSeconds(); // 获取秒数

        // 如果月份、日期、小时、分钟或秒数小于10，前面添加一个"0"以确保它们总是两位数
        month = (month < 10 ? "0" : "") + month;
        day = (day < 10 ? "0" : "") + day;
        hours = (hours < 10 ? "0" : "") + hours;
        minutes = (minutes < 10 ? "0" : "") + minutes;
        seconds = (seconds < 10 ? "0" : "") + seconds;

        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    }

    function getName(path) {
        if (path.indexOf('/') !== -1) {
            path = path.substring(path.lastIndexOf("/") + 1, path.length)
        }
        if (path.indexOf("\\") !== -1) {
            path = path.substring(path.lastIndexOf("\\") + 1, path.length)
        }
        return path
    }

    layui.use(['table', 'jquery'], function () {
        var table = layui.table;
        var upload = layui.upload;
        var $ = layui.jquery
        loading()
        var currentPath = ''
        // 创建渲染实例
        table.render({
            elem: '#test',
            url: '/file/list', // 此处为静态模拟数据，实际使用时需换成真实接口
            where: {
                path: '${path!}'
            },
            page: false,
            height: '500px',
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {
                    field: 'name', width: 250, title: '名称', sort: true, templet: function (d) {
                        return '<a style="color: blue" href="javascript:;" class="name" type="' + d.isFolder +
                            '" fpath="' + d.path + '">' + d.name + '</a>'
                    }
                },
                // 模板 - 函数写法
                {
                    field: 'size', width: 120, title: '大小', sort: true, templet: function (d) {
                        return d.isFolder ? '-' : d.size;
                    }
                },
                {
                    field: 'isFolder', width: 100, title: '类型', sort: true, templet: function (d) {
                        return d.isFolder ? '目录' : '文件';
                    }
                },
                {
                    field: 'lastUpdateTime', width: 170, title: '最后修改时间', sort: true, templet: function (d) {
                        return fDate(new Date(d.lastUpdateTime));
                    }
                },
                {fixed: 'right', title: '操作', width: 300, minWidth: 300, toolbar: '#barDemo'}
            ]],
            parseData: function (res) {
                if (res.code === 0) {
                    $('#path').val(res.data.path)
                    currentPath = res.data.path.replaceAll('\\', '/')
                }
                var list = []
                if (res.data)
                    list = res.data.list
                return {
                    "code": res.code, // 解析接口状态
                    "msg": res.msg, // 解析提示文本
                    "data": list // 解析数据列表
                };
            }
        });

        // 工具栏事件
        table.on('toolbar(test)', function (obj) {
            if (obj.event === 'back') {
                loading()
                table.reloadData('test', {
                    where: {
                        path: currentPath,
                        isBack: true
                    }
                }, true);
            } else if (obj.event === 'refresh') {
                loading()
                table.reloadData('test', {
                    where: {
                        path: currentPath,
                        isBack: false
                    }
                }, true);
            } else if (obj.event === 'packageDownload') {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var arr = checkStatus.data;
                if (arr.length === 0) {
                    layer.msg('还未选中要打包下载的文件/文件夹')
                } else {
                    var list = []
                    for (var item of arr) {
                        list.push(item.path.replaceAll('\\', '/'))
                    }
                    window.open('/file/downloadZipList?list=' + JSON.stringify(list))
                }
            } else if (obj.event === 'moveFile') {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var arr = checkStatus.data;
                if (arr.length === 0) {
                    layer.msg('还未选中要移动的文件/文件夹')
                } else {
                    var list = []
                    for (var item of arr) {
                        list.push(item.path.replaceAll('\\', '/'))
                    }
                    layer.prompt({
                        title: '输入要移动到的位置', formType: 0, placeholder: "文件已存在则覆盖",
                    }, function (val, index) {
                        $.ajax({
                            data: {
                                list: JSON.stringify(list),
                                path: val.replaceAll('\\', '/')
                            },
                            url: '/file/move',
                            type: 'post',
                            success(res) {
                                layer.msg(res.msg)
                                if (res.code === 0)
                                    setTimeout(function () {
                                        window.location.reload()
                                    }, 1200)
                            }
                        })
                    });
                }
            } else if (obj.event === 'copyFile') {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var arr = checkStatus.data;
                if (arr.length === 0) {
                    layer.msg('还未选中要复制的文件/文件夹')
                } else {
                    var list = []
                    for (var item of arr) {
                        list.push(item.path.replaceAll('\\', '/'))
                    }
                    layer.prompt({
                        title: '输入要复制到的位置', formType: 0, placeholder: "文件已存在则覆盖",
                    }, function (val, index) {
                        $.ajax({
                            data: {
                                list: JSON.stringify(list),
                                path: val.replaceAll('\\', '/')
                            },
                            url: '/file/copy',
                            type: 'post',
                            success(res) {
                                layer.msg(res.msg)
                                if (res.code === 0)
                                    setTimeout(function () {
                                        window.location.reload()
                                    }, 1200)
                            }
                        })
                    });
                }
            }
        });

        // 触发单元格工具事件
        table.on('tool(test)', function (obj) { // 双击 toolDouble
            var data = obj.data; // 获得当前行数据
            if (obj.event === 'open') {
                loading()
                if (data.isFolder) {
                    // 数据重载 - 参数叠加
                    table.reloadData('test', {
                        where: {
                            path: data.path.replaceAll('\\', '/'),
                            isBack: false
                        }
                    }, true);
                } else {
                    window.open('/file/open?path=' + data.path.replaceAll('\\', '/'))
                }
            } else if (obj.event === 'download') {
                window.open('/file/downloadZip?path=' + data.path.replaceAll('\\', '/'))
            } else if (obj.event === 'delete') {
                layer.confirm('确认要删除: ' + data.path, {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.ajax({
                        data: {path: data.path.replaceAll('\\', '/')},
                        url: '/file/deletePath',
                        type: 'post',
                        success(res) {
                            layer.msg(res.msg)
                            if (res.code === 0)
                                setTimeout(function () {
                                    window.location.reload()
                                }, 1200)
                        }
                    })
                });
            } else if (obj.event === 'rename') {
                layer.prompt({
                    title: '请输入新的名称', value: getName(data.path), formType: 0, placeholder: "请输入新的名称",
                }, function (val, index) {
                    $.ajax({
                        data: {
                            name: val,
                            path: data.path.replaceAll('\\', '/')
                        },
                        url: '/file/rename',
                        type: 'post',
                        success(res) {
                            layer.msg(res.msg)
                            if (res.code === 0)
                                setTimeout(function () {
                                    window.location.reload()
                                }, 1200)
                        }
                    })
                });
            }
        });

        $('table').click(function (e) {
            if ($(e.target).hasClass('name')) {
                loading()
                if ($(e.target).attr('type') === 'true') {
                    table.reloadData('test', {
                        where: {
                            path: $(e.target).attr('fpath').replaceAll('\\', '/'),
                            isBack: false
                        }
                    }, true);
                } else {
                    window.open('/file/open?path=' + $(e.target).attr('fpath').replaceAll('\\', '/'))
                }
            }
        })

        $('#toFolder').click(function () {
            loading()
            table.reloadData('test', {
                where: {
                    path: $('#path').val().replaceAll('\\', '/'),
                    isBack: false
                }
            }, true);
        })

        // 渲染
        upload.render({
            elem: '#uploadFile', // 绑定多个元素
            url: '/file/uploadPath', // 此处配置你自己的上传接口即可
            data: {
                path: function () {
                    return currentPath.replaceAll('\\', '/');
                }
            },
            accept: 'file', // 普通文件
            done: function (res) {
                layer.msg(res.msg);
                console.log(res);
                if (res.code === 0)
                    setTimeout(function () {
                        window.location.reload()
                    }, 1200)
            }
        });

        $('#toProject').click(function () {
            loading()
            table.reloadData('test', {
                where: {
                    path: '',
                    isProject: true,
                    isBack: false
                }
            }, true);
        })

        function loading() {
            layer.load(2, {icon: 16, shade: 0.1, time: 500});
        }
    });

</script>
</body>
</html>